package com.kintreda.ieco_server.module.api.web;

import com.kintreda.ieco_server.bean.account.Organization;
import com.kintreda.ieco_server.bean.account.User;
import com.kintreda.ieco_server.bean.attention.Attention;
import com.kintreda.ieco_server.bean.goods.Places;
import com.kintreda.ieco_server.bean.order.RecycleRecord;
import com.kintreda.ieco_server.bean.org.OrgSetting;
import com.kintreda.ieco_server.bean.param.Echar;
import com.kintreda.ieco_server.bean.user.Statistics;
import com.kintreda.ieco_server.core.repository.IBaseRepository;
import com.kintreda.ieco_server.core.web.BaseController;
import com.kintreda.ieco_server.core.web.R;
import com.kintreda.ieco_server.module.account.service.IUserService;
import com.kintreda.ieco_server.module.attention.service.IAttentionService;
import com.kintreda.ieco_server.module.order.service.*;
import com.kintreda.ieco_server.module.organization.service.IOrgSettingService;
import com.kintreda.ieco_server.module.organization.service.IOrganizationService;
import com.kintreda.ieco_server.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 组织机构Controller
 *
 * @Created by IntelliJ IDEA
 * @Project_Name ieco_server
 * @Package com.kintreda.ieco_server.module.organization.web
 * @Author ZhongYao_H
 * @Date 2019/4/28:17:36
 * @Year 2019 Month 04 Day 28
 * @Date_zh 2019 年 四月 星期日
 */
@Controller
@RequestMapping("/api/organ")
public class ApiOrganController extends BaseController {

    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    IBaseRepository<RecycleRecord,String> recycleRecordService;
    @Autowired
    IBaseRepository<Organization,String> orgRepository;
    @Autowired
    private IAttentionService attentionService;
    @Autowired
    private IStatisticsService statisticsService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBuyRecordService buyRecordService;
    @Autowired
    private IWasteService wasteService;
    @Autowired
    private IRecycleRecordService recyService;
    @Autowired
    private IUsageRecordService usageRecordService;
    @Autowired
    private IOrgSettingService orgSettingService;
    @Autowired
    private IPlacesService placesService;

    /**
     *
     * 小程序端查询机构
     *
     * @param keyword
     * @return
     */
    @RequestMapping(value = "/search",method = RequestMethod.POST)
    @ResponseBody
    public Object apiQuery( String keyword) throws IOException {
        if (keyword.equals("")){
            return null;
        }
        List<Organization> query = null;
        try {
             query = organizationService.query("from Organization where name like '%"+keyword+"%'  and orgStatus != 1 ", null);
        } catch (Exception e) {
            e.printStackTrace();
            return query;
        }
        return query.toArray();
    }


    /**
     *
     * 查看机构详情
     *
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/getorg",method = RequestMethod.POST)
    @ResponseBody
    public Object getOrg(String orgId,String openid,@RequestParam(value = "type",defaultValue = "3") String type){
        if (openid == null){
            openid = "";
        }

        if (type.equals("1")){
            //查看的是机构的子机构信息
            return getChildOrgInfor(openid,orgId);
        }

        Organization organiza = organizationService.get(orgId);


        String userId = userService.findUserByOpenId(openid).getId();

        Statistics statistics = statisticsService.getByOrgId(orgId);
        if (statistics==null){
            statistics = new Statistics();
            statistics.setOrgId(orgId);
            statisticsService.saveOrUpdate(statistics);
        }
        JdbcTemplate jdbcTemplate = statisticsService.getJdbcTemplate();

        //购袋
        double sackcount = buyRecordService.countByOrgId(orgId);
        statistics.setSackNum(sackcount+"");

        //余额
        BigDecimal orgbalance = statisticsService.getOrgStatistics(orgId).getBalance();
        try {
            statistics.setBalance( orgbalance);
        }catch (Exception e){
            e.printStackTrace();
        }
        //装车
        Long close = recyService.countCloseByOrgId(orgId);
        statistics.setCar(Double.parseDouble(close.toString()));

        //环保值
        Map<String, Object> ePValue = recyService.ePValue(orgId);


        //认领
        Places places = placesService.getByOrgId(organiza.getAdminId(),organiza.getId(), "1");
        if (places!=null){
            statistics.setClaim(places.getNum());
        }else {
            statistics.setClaim("0");

        }

        //点赞

        //!!!!!!!!!! 使用sum求和 返回list一定有一个元素但是元素可能是null

        //总计投递
        List<Long> longs = jdbcTemplate.queryForList("select sum(total) from recyclerecord where userId in (select id from common_user where orgId = ?)", new Object[]{orgId}, Long.class);
        try{
            Long s = longs.size()>0?longs.get(0):0;
            statistics.setSumBalance(s+"");
        }catch (Exception e){
            e.printStackTrace();
            statistics.setSumBalance("0");
        }


        List<Long> gross = jdbcTemplate.queryForList("select sum(gross) from recyclerecord where userId in (select id from common_user where orgId = ?)", new Object[]{orgId}, Long.class);
        try{
            Long gro = gross.size()>0?gross.get(0):0;
            statistics.setDeliveryQuantity(gro+"");
        }catch (Exception e){
            e.printStackTrace();
            statistics.setDeliveryQuantity("0");
        }

        //回收物品饼状图数据
        Object wasteData = wasteService.wasteDataByOrgId(orgId);

        //子机构
        Object childOrg = getChildOrg(orgId);

        //回收记录
        List<Map<String, Object>> recyList = recyService.getOrgListByOrgId(orgId);

        //收集中的袋子
        List<Map<String, Object>> usageRecordList = usageRecordService.queryOrgUsageRecordList(orgId);

        //关注机构用户
        List<Map<String, Object>> focusUser = attentionService.getFocusUser(orgId);

        //不当次数
        List<Long> unsuitables = jdbcTemplate.queryForList("select count(id) from unsuitable where userId in (select id from common_user where orgId = ?) and status = ? ", new Object[]{orgId,"1"}, Long.class);
        Long unsuitable = unsuitables.size()>0?unsuitables.get(0):0;
        statistics.setMisconductNum(unsuitable+"");

        //收运信息
        OrgSetting orgSetting;

        if (organiza.getNature().equals("1")){
            orgSetting = orgSettingService.getByOrgId(organiza.getOrgid());
        }else {
            orgSetting = orgSettingService.getByOrgId(orgId);
        }


        //统计近五个月的投递量
        List<Object> dates = DateUtil.getMonths(5);
        List<Object> echars = new ArrayList<>();
        int i =0;
        for (Object date : dates) {
            Echar echar = new Echar();
            try {
                List<Long> total = jdbcTemplate.queryForList("SELECT sum(gross) from recyclerecord where orgId = ?  and date_format(createDate,'%Y-%m')= ? ", new Object[]{orgId,date}, Long.class);
                Long methon = total.get(0);
                echar.setMonth(dates.get(i).toString());
                if (methon==null){
                    echar.setTotal("0");
                }else {
                    echar.setTotal(methon+"");
                }

            }catch (Exception e){
                echar.setMonth(dates.get(i).toString());
                echar.setTotal("0");
                e.printStackTrace();
            }
            echars.add(echar);
            i++;
        }


        Organization organization = organizationService.get(orgId);
        R   r  = R.ok();
        r.put("org",organization);
        Boolean isfocus = attentionService.isFocus(userId, orgId);
        r.put("isfocus",isfocus);
        r.put("statistics",statistics);
        r.put("wasteData",wasteData);
        r.put("childOrg",childOrg);
        r.put("focusUser",focusUser);
        r.put("recyList",recyList);
        r.put("usageList",usageRecordList);
        r.put("echar",echars);
        r.put("orgSetting",orgSetting);
        r.put("epvalue",ePValue);
        return r;
    }




    private R getChildOrgInfor(String openid ,String orgId){
        Organization organiza = organizationService.get(orgId);
        String userId = userService.findUserByOpenId(openid).getId();

        Statistics statistics = statisticsService.getByUserIdAndType(organiza.getAdminId(),"1");
        if (statistics==null){
            statistics = new Statistics();
            statistics.setOrgId(orgId);
            statisticsService.saveOrUpdate(statistics);
        }
        JdbcTemplate jdbcTemplate = statisticsService.getJdbcTemplate();

        //购袋
        double sackcount = buyRecordService.getCountByOrgAdminId(orgId);
        statistics.setSackNum(sackcount+"");

        //余额
        try {
            BigDecimal orgbalance = statisticsService.getByUserIdAndType(organiza.getAdminId(),"1").getBalance();
            statistics.setBalance( orgbalance);
        }catch (Exception e){
            e.printStackTrace();
        }
        //装车
        Long close = recyService.countCloseByUserId(organiza.getAdminId());
        statistics.setCar(Double.parseDouble(close.toString()));


        //环保值
        Map<String, Object> ePValue = recyService.ePValueByUserId(organiza.getAdminId());


        //认领
        Places places = placesService.getByAdminId(organiza.getAdminId(), "1");
        if (places!=null){
            statistics.setClaim(places.getNum());
        }else {
            statistics.setClaim("0");

        }


        //点赞

        //!!!!!!!!!! 使用sum求和 返回list一定有一个元素但是元素可能是null

        //总计投递
        List<Long> longs = jdbcTemplate.queryForList("select sum(total) from recyclerecord where userId in (select adminId from organization where id = ?)", new Object[]{orgId}, Long.class);
        try{
            Long s = longs.size()>0?longs.get(0):0;
            statistics.setSumBalance(s+"");
        }catch (Exception e){
            e.printStackTrace();
            statistics.setSumBalance("0");
        }


        List<Long> gross = jdbcTemplate.queryForList("select sum(gross) from recyclerecord where userId in (select adminId from organization where id = ?)", new Object[]{orgId}, Long.class);
        try{
            Long gro = gross.size()>0?gross.get(0):0;
            statistics.setDeliveryQuantity(gro+"");
        }catch (Exception e){
            e.printStackTrace();
            statistics.setDeliveryQuantity("0");
        }

        //回收物品饼状图数据
        Object wasteData = wasteService.wasteDataByUserId(organiza.getAdminId());

        //子机构
        Object childOrg = getChildOrg(orgId);

        //回收记录
        List<Map<String, Object>> recyList = recyService.getOrgListByUserId(orgId);

        //收集中的袋子
        List<Map<String, Object>> usageRecordList = usageRecordService.queryUserUsageRecordList(orgId);

        //关注机构用户
        List<Map<String, Object>> focusUser = attentionService.getFocusUser(orgId);

        //不当次数
        List<Long> unsuitables = jdbcTemplate.queryForList("select count(id) from unsuitable where userId = ? and status = ? ", new Object[]{organiza.getAdminId(),"1"}, Long.class);
        Long unsuitable = unsuitables.size()>0?unsuitables.get(0):0;

        statistics.setMisconductNum(unsuitable+"");

        //收运信息
        OrgSetting orgSetting;

        if (organiza.getNature().equals("1")){

            orgSetting = orgSettingService.getByOrgId(organiza.getOrgid());
        }else {

            orgSetting = orgSettingService.getByOrgId(orgId);
        }


        //统计近五个月的投递量
        List<Object> dates = DateUtil.getMonths(5);
        List<Object> echars = new ArrayList<>();
        int i =0;
        for (Object date : dates) {
            Echar echar = new Echar();
            try {
                List<Long> total = jdbcTemplate.queryForList("SELECT sum(gross) from recyclerecord where userId = ?  and date_format(createDate,'%Y-%m')= ? ", new Object[]{organiza.getAdminId(),date}, Long.class);
                Long methon = total.get(0);
                echar.setMonth(dates.get(i).toString());
                if (methon==null){
                    echar.setTotal("0");
                }else {
                    echar.setTotal(methon+"");
                }

            }catch (Exception e){
                echar.setMonth(dates.get(i).toString());
                echar.setTotal("0");
                e.printStackTrace();
            }
            echars.add(echar);
            i++;
        }


        Organization organization = organizationService.get(orgId);
        R   r  = R.ok();
        r.put("org",organization);
        Boolean isfocus = attentionService.isFocus(userId, orgId);
        r.put("isfocus",isfocus);
        r.put("statistics",statistics);
        r.put("wasteData",wasteData);
        r.put("childOrg",childOrg);
        r.put("focusUser",focusUser);
        r.put("recyList",recyList);
        r.put("usageList",usageRecordList);
        r.put("echar",echars);
        r.put("orgSetting",orgSetting);
        r.put("epvalue",ePValue);
        return r;
    }



    /***
     *
     * get 排行榜前五名机构
     *
     *
     * @return
     */
    @RequestMapping(value = "/top",method = RequestMethod.POST)
    @ResponseBody
    public Object qpiQueryTop(){
        List<Map<String, Object>> top5 = orgRepository.findListBySql("SELECT t1.id ,t1.name,t1.icon from organization t1 WHERE t1.orgStatus = 2 and t1.orgid is null   ORDER  BY   ( SELECT sum(gross) from recyclerecord where userId in (SELECT id from common_user where orgid = t1.id) ) DESC LIMIT 0 ,5", null);
        for (Map<String, Object> map : top5) {
            List<Map<String, Object>> sum = recycleRecordService.findListBySql("select sum(gross) as sum from recyclerecord where orgId = ? ", new Object[]{map.get("id")});
            Object groos = "0";
            try{
                 groos = sum.get(0).get("sum");
                BigDecimal groosBigdecimal = new BigDecimal(groos.toString());
                map.put("sum",formatToNumber(groosBigdecimal));
            }catch (Exception e){
                map.put("sum",groos);
            }


        }

        return top5;
    }


    /**
     *
     * get关注机构
     * @param openid
     * @return
     */
    @RequestMapping("/orglist")
    @ResponseBody
    public Object getFocusOrg(String openid){
        //TODO 验证用户登录逻辑
        try {
            String  userId = userService.findUserByOpenId(openid).getId();
            List<Attention> focusOrg = attentionService.getFocusOrg(userId);
            List<Organization> result = new LinkedList<>();
            for (Attention attention : focusOrg) {
                result.add(organizationService.get(attention.getOrgId()));
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @RequestMapping(value = "/apply",method = RequestMethod.POST)
    @ResponseBody
    public Object orgApply(Organization organization,String openId,String lat,String lon,
                           String adminName,String administratorTel,String name,String ein,
                           String financial, String address,String number,String invoice,String financialTel ,String type){


        try {
            String adminId = userService.findUserByOpenId(openId).getId();

            if (organizationService.isApply(adminId,1)){
                return R.error("已经在申请中,请勿重复申请");
            }

            if (organizationService.isApply(adminId,2)){
                return  R.error("已申请通过,请勿重复申请");
            }

            if (organizationService.isExist(organization.getName())){
                return R.error("机构名称已存在!");
            }
            organization.setEin(ein);
            organization.setNumber(number);
            organization.setAdministratorTel(financialTel);
            organization.setFinancial(financial);
            organization.setInvoice(invoice);
            organization.setName(name);
            organization.setAddress(address);
            organization.setAdminName(adminName);
            organization.setAdministratorTel(administratorTel);
            organization.setAdminId(adminId);
            organization.setLatitude(lat);
            organization.setLongitude(lon);
            organization.setNature("0");
            organization.setOrgStatus(1);
            organization.setType(type);
            organizationService.save(organization);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("系统异常稍后重试!");
        }
        return R.ok("提交成功!");

    }

    @RequestMapping(value = "/bing",method = RequestMethod.POST)
    @ResponseBody
    public Object bingOrg(String code,String openid){
        try{

            User user = userService.findUserByOpenId(openid);
            Organization organization = organizationService.findByCode(code);
            if (organization==null){
                return R.error("邀请码无效!");
            }
            user.setOrgId(organization.getId());
            user.setType("4");
            userService.update(user);
            return R.ok("绑定成功!");

        }catch (NullPointerException e){
            e.printStackTrace();
            return R.error("异常稍后重试!");
        }

    }
    @RequestMapping(value = "/isbing",method = RequestMethod.POST)
    @ResponseBody
    public Object isBing(String openid){
        User user = userService.findUserByOpenId(openid);
        try {
            if (user.getOrgId().equals("") || user.getOrgId().equals(null)){
                return R.ok("未绑定").put("isbing",false);
            }
            return R.error("已绑定").put("isbing",true);
        }catch (NullPointerException e){
            e.printStackTrace();
            return R.ok("未绑定").put("isbing",false);
        }




    }


    /**
     * 查询机构是否允许提现
     *
     * @param openid
     * @return
     */
    @RequestMapping(value = "/isdeposit",method = RequestMethod.POST)
    @ResponseBody
    public Object isDeposit(String openid){
        try {
            User user = userService.findUserByOpenId(openid);
            if (!user.getType().equals("3")){
                return null;
            }

            Organization organization = organizationService.getOrgByAdminIdAndOrgStatus(user.getId());
            if (organization==null){
                return null;
            }
            Integer isdeposit = organization.getAllow();
            if (isdeposit==0){
                return R.error();
            }
            if (isdeposit==1){
                return R.ok();
            }

            return R.error();

        }catch (NullPointerException e){
            e.printStackTrace();
            return R.error();
        }

    }

    /**
     *
     * 设置是否允许提现
     *
     *
     * @param openid
     * @return
     */
    @RequestMapping(value = "/allow",method = RequestMethod.POST)
    @ResponseBody
    public Object allow(String openid,Integer allow){
        try {

            String userId = userService.findUserByOpenId(openid).getId();
            Organization organization = organizationService.getOrgByAdminIdAndOrgStatus(userId);
            organization.setAllow(allow);
            organizationService.update(organization);
            return R.ok();

        }catch (NullPointerException e){
            e.printStackTrace();
            return R.error();
        }

    }



    public Object getChildOrg(String orgId){
        List<Map<String, Object>> mapList = orgRepository.findListBySql("select id,name,adminId from organization where orgId = ? and adminId != ? ", new Object[]{orgId,""});
        for (Map<String, Object> map : mapList) {
            String adminId = map.get("adminId").toString();
            if (!StringUtils.equals(adminId,"")){
                Statistics statistics = statisticsService.getByUserIdAndType(adminId, "1");
                if (statistics!=null){
                    String balance = statistics.getBalance().toString();
                    map.put("balance",balance);
                }else {
                    map.put("balance","0");
                }

            }
        }

        return mapList;
    }

    public static String formatToNumber(BigDecimal obj) {
        DecimalFormat df = new DecimalFormat("#.00");
        if(obj.compareTo(BigDecimal.ZERO)==0) {
            return "0.00";
        }else if(obj.compareTo(BigDecimal.ZERO)>0&&obj.compareTo(new BigDecimal(1))<0){
            return "0"+df.format(obj).toString();
        }else {
            return df.format(obj).toString();
        }
    }




}
